from django.db import models
from django.db.models import Max

from users.models import UserInfo


class Unit(models.Model):
    """计量单位"""
    name = models.CharField(verbose_name='单位', max_length=12)
    remark = models.CharField(verbose_name='单位说明', max_length=64, blank=True, null=True)
    sort = models.IntegerField(verbose_name='排序号', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '计量单位'
        verbose_name_plural = verbose_name
        ordering = ["sort"]


class StoreHouse(models.Model):
    """仓库表"""
    FLAGS = (
        (0, '否'),
        (1, '是'),
    )
    name = models.CharField(verbose_name='仓库名称', max_length=64)
    address = models.CharField(verbose_name='仓库地址', max_length=128, blank=True, null=True)
    flag = models.IntegerField(verbose_name='默认仓库', choices=FLAGS, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '仓库管理'
        verbose_name_plural = verbose_name


class Category(models.Model):
    """商品类别"""
    name = models.CharField(verbose_name='类别名称', max_length=12)
    parent = models.ForeignKey('self', verbose_name='上级类别', related_name='children', on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    path = models.CharField(verbose_name='路径', null=True, blank=True, max_length=256)
    remark = models.CharField(verbose_name='类别说明', max_length=64, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '商品类别'
        verbose_name_plural = verbose_name

    def save(self, *args, **kwargs):
        if self.id is None:
            b_exists = self.__class__.objects.all().exists()
            if not b_exists:
                self.id = 100001
        return super().save(*args, **kwargs)


class CustSuppClass(models.Model):
    """客商分类"""
    name = models.CharField(verbose_name='客商分类', max_length=24)
    parent = models.ForeignKey('self', verbose_name='上级客商分类', related_name='children', on_delete=models.CASCADE, blank=True, null=True,
                               db_constraint=False)
    path = models.CharField(verbose_name='路径', null=True, blank=True, max_length=256)
    remark = models.CharField(verbose_name='分类说明', max_length=64, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '客商分类'
        verbose_name_plural = verbose_name

    def save(self, *args, **kwargs):
        if self.id is None:
            b_exists = self.__class__.objects.all().exists()
            if not b_exists:
                self.id = 100001
        return super().save(*args, **kwargs)


class CustomSupplier(models.Model):
    """客户供应商"""
    code = models.CharField(verbose_name='客户编号', max_length=12, blank=True, null=True)
    name = models.CharField(verbose_name='客户名称', max_length=128)
    cate = models.ForeignKey(to='CustSuppClass', verbose_name='客商分类', on_delete=models.SET_NULL, db_constraint=False, blank=True, null=True)
    linkman = models.CharField(verbose_name='联系人', max_length=64, blank=True, null=True)
    telephone = models.CharField(verbose_name='电话', max_length=32, blank=True, null=True)
    fax = models.CharField(verbose_name='传真', max_length=32, blank=True, null=True)
    email = models.CharField(verbose_name='邮箱', max_length=32, blank=True, null=True)
    bank = models.CharField(verbose_name='开户行', max_length=64, blank=True, null=True)
    account = models.CharField(verbose_name='银行账户', max_length=32, blank=True, null=True)
    tax_code = models.CharField(verbose_name='税号', max_length=16, blank=True, null=True)
    help_code = models.CharField(verbose_name='助记码', max_length=32, blank=True, null=True)
    is_customer = models.BooleanField(verbose_name='是否是客户', blank=True, null=True)
    is_supplier = models.BooleanField(verbose_name='是否是供应商', blank=True, null=True)
    is_vip = models.IntegerField(verbose_name='vip会员', choices=((0, '普通客户'), (1, 'vip会员')), blank=True, null=True)
    address = models.CharField(verbose_name='地址', max_length=128, blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)
    user = models.ForeignKey(to=UserInfo, verbose_name='创建人', blank=True, null=True, on_delete=models.SET_NULL,
                             db_constraint=False)
    active_point = models.FloatField(verbose_name='活动积分', blank=True, null=True)
    member_point = models.FloatField(verbose_name='会员积分', blank=True, null=True)
    consume_point = models.FloatField(verbose_name='消费积分', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '客户供应商'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        max_code = cls.objects.all().aggregate(max_code=Max("code"))
        max_value = max_code['max_code']
        if max_value is None:
            code = '0001'
            return code
        else:
            code = str(int(max_value) + 1).rjust(4, '0')
            return code

    def save(self, *args, **kwargs):
        if self.code == "" or self.code is None:
            self.code = self.__class__.get_max_code()
        else:
            if self.id is None:
                exists = self.__class__.objects.filter(code=self.code).exists()
                if exists:
                    self.code = self.__class__.get_max_code()

        return super().save(*args, **kwargs)


class Goods(models.Model):
    """商品管理"""
    code = models.CharField(verbose_name='商品编号', unique=True, max_length=12)
    name = models.CharField(verbose_name='商品名称', max_length=64)
    cate = models.ForeignKey(to=Category, verbose_name='商品类别', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    unit = models.ForeignKey(to=Unit, verbose_name='计量单位', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    bar_code = models.CharField(verbose_name='条码', max_length=32, blank=True, null=True)
    help_code = models.CharField(verbose_name='助记码', max_length=12, blank=True, null=True)
    supplier = models.ForeignKey(to='CustomSupplier', verbose_name='供应商', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    specs = models.CharField(verbose_name='规格', max_length=32, blank=True, null=True)
    brand = models.CharField(verbose_name='品牌', max_length=32, blank=True, null=True)
    place = models.CharField(verbose_name='产地', max_length=64, blank=True, null=True)
    purchase_price = models.FloatField(verbose_name='采购单价', blank=True, null=True)
    sale_price = models.FloatField(verbose_name='销售单价', blank=True, null=True)
    discount = models.IntegerField(verbose_name='会员折扣', blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)
    user = models.ForeignKey(to=UserInfo, verbose_name='创建人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '商品管理'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        format_code = 'SPBH'
        max_code = cls.objects.all().aggregate(max_code=Max("code"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '000001'
            code = "{}{}".format(format_code, num)
            return code
        else:
            num = str(int(max_value[-6:]) + 1).rjust(6, '0')
            code = '{0}{1}'.format(format_code, num)
            return code

    def save(self, *args, **kwargs):
        if self.code == "" or self.code is None:
            self.code = self.__class__.get_max_code()
        else:
            if self.id is None:
                exists = self.__class__.objects.filter(code=self.code).exists()
                if exists:
                    self.code = self.__class__.get_max_code()

        return super().save(*args, **kwargs)


class Company(models.Model):
    """公司信息"""
    name = models.CharField(verbose_name='公司名称', max_length=120)
    credit_code = models.CharField(verbose_name='信用代码', max_length=20, blank=True, null=True)
    address = models.CharField(verbose_name='地址', max_length=150, blank=True)
    telephone = models.CharField(verbose_name='电话', max_length=30, blank=True, null=True)
    fax = models.CharField(verbose_name='传真', max_length=24, blank=True, null=True)
    bank = models.CharField(verbose_name='开户行', max_length=60, blank=True, null=True)
    account = models.CharField(verbose_name='银行账号', max_length=20, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '公司信息'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    def __str__(self):
        return self.name


class Employee(models.Model):
    name = models.CharField(verbose_name='姓名', max_length=24)
    gender = models.CharField(verbose_name='性别', max_length=4, choices=(("男", "男"), ("女", "女")), blank=True, null=True)
    telephone = models.CharField(verbose_name='手机', max_length=16, blank=True, null=True)
    id_card = models.CharField(verbose_name='身份证号', max_length=32, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '员工信息'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class AccountTitle(models.Model):
    """会计科目"""
    name = models.CharField(verbose_name="名称", max_length=32)
    desc = models.CharField(verbose_name='说明', max_length=64, blank=True, null=True)
    parent = models.ForeignKey('self', verbose_name='父项', related_name='children', blank=True, null=True, db_constraint=False, on_delete=models.SET_NULL)
    code = models.CharField(verbose_name='科目编码', max_length=12, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '会计科目'
        verbose_name_plural = verbose_name
        ordering = ['id']
